export default {
    install() {
        const JUST_NOW = 3000 //3s内
        const IN_SECOND = 1000 * 60 //一分钟
        const IN_MINUTE = 1000 * 60 * 60 //一小时
        const IN_HOUR = 1000 * 60 * 60 * 12 //12小时
        const IN_DAY = 1000 * 60 * 60 * 24 * 1 //1天
        const IN_MONTH = 1000 * 60 * 60 * 24 * 30 //1个月

        uni.$u.$timeUtil = {
            /**
             * 时间格式化
             * @param date
             * @param fmt
             * @returns {*}
             */
            formatDate(date: string | number | Date, fmt: string) {
                if (!fmt) {
                    fmt = 'yyyy-MM-dd HH:mm:ss'
                }
                let r = this.toDate(date)
                const o: any = {
                    'y+': r.getFullYear(),
                    'M+': r.getMonth() + 1,
                    'd+': r.getDate(),
                    'H+': r.getHours(),
                    'm+': r.getMinutes(),
                    's+': r.getSeconds(),
                    'S+': r.getMilliseconds(),
                    'q+': Math.floor(r.getMonth() / 3) + 1,
                    'h+': (() => {
                        const hour = r.getHours() % 12
                        return hour === 0 ? 12 : hour
                    })(),
                    'E+': (() => {
                        const week: any = {
                            '0': 'Sunday',
                            '1': 'Monday',
                            '2': 'Tuesday',
                            '3': 'Wednesday',
                            '4': 'Thursday',
                            '5': 'Friday',
                            '6': 'Saturday'
                        }
                        return week[String(r.getDay())]
                    })(),
                    'e+': (() => {
                        const week: any = {
                            '0': 'Sun',
                            '1': 'Mon',
                            '2': 'Tue',
                            '3': 'Wed',
                            '4': 'Thu',
                            '5': 'Fri',
                            '6': 'Sat'
                        }
                        return week[r.getDay() + '']
                    })(),
                    x1: (() => {
                        const week: any = {
                            '0': '周日',
                            '1': '周一',
                            '2': '周二',
                            '3': '周三',
                            '4': '周四',
                            '5': '周五',
                            '6': '周六'
                        }
                        return week[r.getDay() + '']
                    })(),
                    x2: (() => {
                        const hour = ['凌晨', '早上', '下午', '晚上']
                        const h = r.getHours()
                        if (h === 12) {
                            return '中午'
                        }
                        return hour[Math.floor(h / 6)]
                    })()
                }
                for (let k in o) {
                    if (new RegExp('(' + k + ')', 'g').test(fmt)) {
                        const len = RegExp.$1.length
                        fmt = fmt.replace(RegExp.$1, len == 1 ? o[k] : ('00' + o[k]).substr(-len))
                    }
                }
                return fmt
            },
            padLeftZero(str: string) {
                return ('00' + str).substr(str.length)
            },
            str2Date(dateStr: string, separator: string) {
                if (!separator) {
                    separator = '-'
                }
                let dateArr = dateStr.split(separator)
                let year = parseInt(dateArr[0])
                let month
                //处理月份为04这样的情况
                if (dateArr[1].indexOf('0') == 0) {
                    month = parseInt(dateArr[1].substring(1))
                } else {
                    month = parseInt(dateArr[1])
                }
                let day = parseInt(dateArr[2])
                let date = new Date(year, month - 1, day)
                return date
            },
            /**
             * 时间转化
             */
            toDate(date: string | number | Date) {
                let re: Date = new Date()
                if (typeof date === 'string') {
                    re = new Date(date.replace(/-/g, '/'))
                }
                if (typeof date === 'number') {
                    re = new Date(date)
                }
                return re
            },
            /**
             * 倒计时
             * @param beginDate
             * @param endDate
             * @returns {{}}
             */
            getCountDownTimeNum(beginDate: string | number | Date, endDate: string | number | Date) {
                let countDown = {}
                let times = (this.toDate(endDate).getTime() - this.toDate(beginDate).getTime()) / 1000
                if (times > 0) {
                    let day = Math.floor(times / (24 * 60 * 60)) //计算整数天数
                    let afterDay = times - day * 24 * 60 * 60 //取得算出天数后剩余的秒数
                    let hour = Math.floor(afterDay / (60 * 60)) //计算整数小时数
                    let afterHour = times - day * 24 * 60 * 60 - hour * 60 * 60 //取得算出小时数后剩余的秒数
                    let min = Math.floor(afterHour / 60) //计算整数分
                    let afterMin = times - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60 //取得算出分后剩余的秒数
                    countDown = {
                        day: day,
                        hour: hour,
                        minute: min,
                        second: afterMin
                    }
                }
                return countDown
            },
            chatTimeFormat(time: any) {
                let str
                let d = this.toDate(time)
                const now = new Date()
                const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
                const yesterday = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1)
                const beforeYesterday = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 2)
                const monday = new Date(today)
                monday.setDate(today.getDate() - (today.getDay() ? today.getDay() - 1 : 6))
                //注意：date初始化默认是按本地时间初始的，但打印默认却是按GMT时间打印的，也就是说打印出的不是本地现在的时间
                //LocaleString的打印也有点问题，"0点"会被打印为"上午12点"
                if (d.getTime() > today.getTime()) {
                    str = ''
                } else if (d.getTime() > yesterday.getTime()) {
                    str = '昨天'
                } else if (d.getTime() > beforeYesterday.getTime()) {
                    str = '前天'
                } else if (d.getTime() > monday.getTime()) {
                    const week: any = {
                        '0': '周日',
                        '1': '周一',
                        '2': '周二',
                        '3': '周三',
                        '4': '周四',
                        '5': '周五',
                        '6': '周六'
                    }
                    str = week[d.getDay() + '']
                } else {
                    const hour = ['凌晨', '早上', '下午', '晚上']
                    const h = d.getHours()
                    if (h === 12) str = '中午'
                    else str = hour[Math.floor(h / 6)]
                    str = this.formatDate(d, 'MM月dd ') + str
                }
                str += this.formatDate(d, str ? ' HH:mm' : 'HH:mm')
                return str
            },
            getChatTime(sTime: string | number | Date, dTime: string | number | Date) {
                let dDate = this.toDate(dTime)
                if (sTime) {
                    let sDate = this.toDate(sTime)
                    let times = (dDate.getTime() - sDate.getTime()) / 1000
                    // 超过5分钟
                    if (times && times / 60 > 5) {
                        return this.chatTimeFormat(dDate)
                    } else {
                        return ''
                    }
                } else {
                    return this.chatTimeFormat(dDate)
                }
            },
            getNumberMonth(month: string) {
                switch (month) {
                    case 'Jan':
                        return '1'
                    case 'Feb':
                        return '2'
                    case 'Mar':
                        return '3'
                    case 'Apr':
                        return '4'
                    case 'May':
                        return '5'
                    case 'June':
                    case 'Jun':
                        return '6'
                    case 'July':
                    case 'Jul':
                        return '7'
                    case 'Aug':
                        return '8'
                    case 'Sept':
                    case 'Sep':
                        return '9'
                    case 'Oct':
                        return '10'
                    case 'Nov':
                        return '11'
                    case 'Dec':
                        return '12'
                }
            },
            /**
             * 聊天列表事件展示
             * @param time
             * @returns {string}
             */
            updateTimeShow(time: string | number | Date) {
                let localTime = new Date().getTime() //当前系统时间
                let createTime = new Date(time).getTime() //消息创建时间
                let diff = localTime - createTime
                if (diff <= JUST_NOW) return '刚刚'
                else if (diff <= IN_SECOND) return '1分钟内'
                else if (diff <= IN_MINUTE) return Math.floor(diff / IN_SECOND) + '分钟前'
                else if (diff <= IN_MINUTE) return Math.floor(diff / IN_MINUTE) + '小时前'
                else if (diff <= IN_HOUR * 2) {
                    const list = createTime.toString().split(' ')
                    const lastIndex = list[4].lastIndexOf(':')
                    const realtime = list[4].toString().substring(0, lastIndex)
                    return realtime
                } else if (diff <= IN_DAY * 2) {
                    return '昨天'
                } else if (diff <= IN_DAY * 3) {
                    return '前天'
                } else if (diff < IN_DAY * 7) {
                    if (diff < IN_DAY) {
                        return Math.floor(diff / IN_HOUR) + '天前'
                    }
                    const t = createTime.toString().slice(0, 3)
                    switch (t) {
                        case 'Mon':
                            return '星期一'
                        case 'Tue':
                            return '星期二'
                        case 'Wed':
                            return '星期三'
                        case 'Thu':
                            return '星期四'
                        case 'Fri':
                            return '星期五'
                        case 'Sat':
                            return '星期六'
                        case 'Sun':
                            return '星期日'
                    }
                } else {
                    const list = createTime.toString().split(' ')
                    const month = list[1]
                    let realtime = ''
                    if (diff < IN_MONTH) {
                        realtime += this.getNumberMonth(month)
                    } else {
                        realtime = list[3] + '-' + this.getNumberMonth(month)
                    }
                    return realtime + '-' + list[2]
                }
            }
        }
    }
}
